package com.sh.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.sh.rabbitmq.utils.ChannelFactory;

import java.util.HashMap;
import java.util.Map;

public class Consumer1 {

    //普通交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";

    //普通队列
    public static final String NORMAL_QUEUE = "normal_queue";
    //死信队列
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = ChannelFactory.getChannel();

        //声明普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明死信交换机
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        Map<String, Object> arguments = new HashMap<>(7);
        //队列最大长度
        //arguments.put("x-max-length",6);

        //链接的死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key","lisi");

        //声明普通队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        //声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);

        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");


        DeliverCallback deliverCallback = (var1,var2)->{
            String msg = new String(var2.getBody());
            if(msg.equals("哈哈")){
                channel.basicReject(var2.getEnvelope().getDeliveryTag(),false);
                System.out.println("被拒绝"+msg);
            }else {
                channel.basicAck(var2.getEnvelope().getDeliveryTag(),false);
                System.out.println("接收到的消息："+ msg);
            }

        };

        CancelCallback cancelCallback = var1 ->{
            System.out.println("回调了");
        };

        System.out.println("C1正在等待接收");
        channel.basicConsume(NORMAL_QUEUE,false,deliverCallback,cancelCallback);
    }
}
